import { baseUrl, header } from "@/common/config.js"
import store from '../store/index.js'
// 网络请求
const request = (url = '',method = 'GET',data = {},{isAuth = false,isLoading = false,isForm = false},dataType = 'json') => {
	return new Promise((resolvt,reject) => {
		if(isLoading) {
			uni.showLoading({
				title: '加载中...'
			})
		}
		let header = {
			'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
		}
		// 判断是否需要登录
		if(isAuth) {
			header = {
				"Authorization": store.state.token
			}
			if(isForm) {
				header = {
					'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
					'Authorization': store.state.token
				}
			}
		}
		uni.request({
			url: baseUrl + url,
			method,
			dataType,
			data: data,
			header: header,
			success: (res) => {
				uni.hideLoading()
				const code = res.data.ret
				// 请求失败处理
				if(code === 404 || code === 0 || code === 400) {
					uni.showToast({
						title: '请求错误',
						icon: 'error'
					})
					return
				}
				if(code === 401 || code === 403) {
					uni.showToast({
						title: '登录凭证过期,请重新登录',
						icon: 'none'
					})
					store.commit('SET_LOGIN',{sess_id: null, user_id: null})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login',
							animationType: 'fade-in'
						})
					},500)
					return
				}
				if(code === 500) {
					uni.showToast({
						title: '系统异常',
						icon: 'error'
					})
					return
				}
				if(code === 405) {
					uni.showModal({
						title: '提示',
						content: res.data.msg,
						showCancel: false,
						confirmText: '知道了',
						success: (e) => {
							
						}
					})
					return
				}
				resolvt(res.data)
			},
			fail: (err) => {
				uni.hideLoading()
				uni.showToast({
					title: '数据加载异常!',
					icon: 'error'
				})
				reject(err)
			}
		})
	})
}

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  request[method] = (api, data, opt) => request(api, method, data, opt || {})
});

// 文件上传
const upload = (url = '',filePath = '',{noAuth = false}) => {
	return new Promise((resolve,reject) => {
		uni.uploadFile({
			 url: baseUrl + url,
			 filePath,
			 method: 'POST',
			 name: 'multipart',
			 formData: {
				 'model': 'user',
				 'pid': 7 
			 },
			 success: res => {
				 let result = JSON.parse(res.data)
				resolve(result)
			 },
			 fail: (err) => {
				 console.log(err)
			 	reject(err)
			 }
		})
	})
}

export default{
	...request,
	upload
}